<template>
	<view class="audit-model-content">
		<view style="background: #ffff;">
			<u-tabs :list="tabsList" @click="tabsClick"></u-tabs>
		</view>

		<view v-show="currentIndex === 0 || !hasFlow" class="audit-content">
			<view class="fx-right" v-if="isCurrentUser || !hasFlow">
				<view v-if="!hasFlow">
					<u-alert :title="`当前选中【${rowLen}】条记录待审核..`" type="success" :closable="false" />
				</view>
				<view class="rd" style="display: flex;margin-bottom: 20rpx;">
					<span>审批：</span>
					<u-radio-group style="margin-left:15px" v-model="auditParam.value">
						<view style="margin-right: 30rpx;" v-for="item in auditParam.data" :key="item.value">
							<u-radio :name="item.value" :label="item.text"></u-radio>
						</view>
					</u-radio-group>
				</view>
				<view style="border: 1px solid #d0d0d0;border-radius: 6rpx;">
					<u--textarea border="none" :height="100" v-model="auditParam.reason" placeholder="请输入审批内容">
					</u--textarea>
				</view>

				<view class="btn">
					<u-button type="primary" shape="square" @click="auditClick">审批</u-button>
				</view>
			</view>
			<view class="fx-left" v-if="hasFlow">
				<view class="v-steps" style="padding-left: 30rpx;">
					<view v-for="(item, index) in workFlowSteps" :key="index">
						<view 
							class="step-item" 
							:class="{'step-item-ad': item.auditId || item.stepAttrType === 'start'}"
							v-if="item.stepAttrType === 'start'"
						>
							<view class="right-item">
								<view class="step-line"></view>
								<i class="step-circle"></i>
								<view class="step-title">{{ item.stepName }}</view>
								<view class="step-text">发起人：{{ item.creator }}</view>
							</view>
						</view>
						<view class="step-item" v-else-if="item.stepAttrType === 'end'">
							<view class="right-item">
								<view class="step-line"></view>
								<i class="step-circle"></i>
								<view class="step-title">{{ item.stepName }}</view>
							</view>
						</view>
						<view v-else :class="{ 'step-current': item.isCurrent }" class="step-item">
							<view class="right-item">
								<view class="step-line"></view>
								<i class="step-circle"></i>
								<view class="step-title">{{ item.stepName }}</view>
								<view class="step-text">审批人：{{ item.auditor }}</view>
								<view class="step-text">状 态： {{ getAuditStatus(item.auditStatus) }}</view>
								<view class="step-text">审批时间： {{ item.auditDate || '待审批' }}</view>
								<view class="step-text">备 注： {{ item.remark || '-' }}</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view v-show="currentIndex === 1">
			<view class="f-item" v-for="(item, index) in formData" :key="index">
				<view class="f-name">{{ item.name }}</view>
				<view class="f-value">{{ item.value }}</view>
			</view>
		</view>

		<view v-show="currentIndex === 2">
			<vol-table 
				titleField="auditDate" 
				:tableData="tableData" 
				:columns="auditColumns" 
				:pagination-hide="true"
				:load-key="false" 
				:text-inline="false" 
				:ck="false"
			>
			</vol-table>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, defineProps, defineEmits } from 'vue'

// 类型定义
interface AuditData {
	workTable: string
	tableKey: string
}

interface TabItem {
	name: string
	inited?: boolean
}

interface WorkFlowStep {
	stepName: string
	stepAttrType: 'start' | 'end' | 'normal'
	auditId?: string
	creator?: string
	auditor?: string
	auditStatus?: number
	auditDate?: string
	remark?: string
	isCurrent?: boolean
	createDate?: string
}

interface AuditParam {
	rows: number
	model: boolean
	value: number
	reason: string
	status: number[]
	data: Array<{ text: string; value: number }>
}

interface FormDataItem {
	name: string
	value: string
}

interface AuditColumn {
	title: string
	field: string
	width: number
	bind?: {
		data: any[]
	}
}

interface DictionaryItem {
	key: string
	value: string
}

interface AuditResponse {
	status: boolean
	list: WorkFlowStep[]
	auditDic: DictionaryItem[]
	log: WorkFlowStep[]
	form: FormDataItem[]
}

// Props
const props = defineProps<{
	data: AuditData
}>()

// Emits
const emit = defineEmits<{
	(e: 'onAudit', data: any): void
}>()

// HTTP工具函数
const http = {
	post: async (url: string, data: any = {}, loading: boolean | string = false): Promise<any> => {
		if (loading) {
			const title = typeof loading === 'string' ? loading : '提交中...'
			uni.showLoading({ title })
		}
		return new Promise((resolve, reject) => {
			uni.request({
				url: url,
				method: 'POST',
				data: data,
				header: {
					'Authorization': getToken(),
					'Content-Type': 'application/json'
				},
				success: (res: any) => {
					if (loading) uni.hideLoading()
					resolve(res.data)
				},
				fail: (err: any) => {
					if (loading) uni.hideLoading()
					reject(err)
				}
			})
		})
	}
}

// 获取token
const getToken = (): string => {
	return uni.getStorageSync('token') || ''
}

// 全局选项存储
let currentOption: { table: string; key: string } = { table: '', key: '' }

// State
const currentIndex = ref<number>(0)
const tabsList = ref<TabItem[]>([
	{ name: '审批' },
	{ name: '详细信息' },
	{ name: '审批记录' }
])
const height = ref<number>(550)
const width = ref<number>(1000)
const workFlowSteps = ref<WorkFlowStep[]>([])
const hasFlow = ref<boolean>(false)
const formData = ref<FormDataItem[]>([])
const isFlow = ref<boolean>(false)

const auditParam = reactive<AuditParam>({
	rows: 0,
	model: false,
	value: -1,
	reason: '',
	status: [0, 2],
	data: [
		{ text: '通过', value: 1 },
		{ text: '拒绝', value: 3 },
		{ text: '驳回', value: 4 }
	]
})

const tableData = ref<any[]>([])
const auditColumns = ref<AuditColumn[]>([
	{
		title: '节点',
		field: 'stepName',
		width: 100
	},
	{
		title: '审批人',
		field: 'auditor',
		width: 80
	},
	{
		title: '审批结果',
		field: 'auditStatus',
		width: 70,
		bind: {
			data: []
		}
	},
	{
		title: '审批时间',
		field: 'auditDate',
		width: 145
	},
	{
		title: '备注',
		field: 'remark',
		width: 120
	}
])

const isCurrentUser = ref<boolean | null>(null)
const activeName = ref<string>('audit')
const auditDic = ref<DictionaryItem[]>([])
const rowLen = ref<number>(0)
const currentRows = ref<any[]>([])

// Methods
const tabsClick = (item: { index: number }): void => {
	console.log(item)
	currentIndex.value = item.index
	tabsList.value[item.index].inited = true
}

const getAuditStatus = (key: number | string): string => {
	const statusItem = auditDic.value.find(x => x.key === String(key))
	return statusItem?.value || String(key) || '待审批'
}

const auditClick = async (): Promise<void> => {
	if (auditParam.value === -1) {
		uni.showToast({ title: '请选择审批项', icon: 'none' })
		return
	}

	const keys = currentRows.value.map(x => x[currentOption.key])
	const url = `api/${currentOption.table}/audit?auditReason=${auditParam.reason}&auditStatus=${auditParam.value}`

	try {
		const result = await http.post(url, keys, '审核中....')
		uni.showToast({ title: result.message || '审批成功', icon: 'none' })
		
		if (!result.status) {
			return
		}
		
		isCurrentUser.value = false
		emit('onAudit', result)
	} catch (error) {
		console.error(error)
		uni.showToast({ title: '审批失败', icon: 'error' })
	}
}

const getAuditInfo = async (option: { table: string; key: string }): Promise<void> => {
	const table = option.table
	const url = `api/Sys_WorkFlow/getSteps?tableName=${table}`
	const ids = currentRows.value.map(x => x[option.key])

	try {
		const result: AuditResponse = await http.post(url, ids, true)
		
		if (!result.status) {
			uni.showToast({ title: result.message || '获取审批信息失败', icon: 'none' })
			return
		}

		hasFlow.value = !!(result.list || []).length
		
		if (!hasFlow.value) {
			const auditStatusField = Object.keys(currentRows.value[0]).find(x => 
				x.toLowerCase() === 'auditstatus'
			)

			if (auditStatusField) {
				const checkStatus = currentRows.value.every((x) => {
					return auditParam.status.some(c => 
						c === x[auditStatusField] || !x[auditStatusField]
					)
				})
				
				if (!checkStatus) {
					uni.showToast({ title: '只能选择待审批或审核中的数据', icon: 'none' })
					return
				}
			}
			
			rowLen.value = currentRows.value.length
			isCurrentUser.value = true
			return
		}

		if (!auditDic.value.length) {
			auditDic.value.push(...(result.auditDic || []))
			auditColumns.value.forEach(item => {
				if (item.field === 'auditStatus') {
					item.bind!.data = auditDic.value
				}
			})
		}

		isCurrentUser.value = result.list.some(x => x.isCurrent)
		
		workFlowSteps.value.length = 0
		workFlowSteps.value.push(...result.list)
		
		tableData.value.length = 0
		result.log.forEach(x => {
			if (x.stepAttrType === 'start') {
				x.stepName = '进入流程'
				x.auditDate = x.createDate
			}
		})
		tableData.value.push(...result.log)
		
		formData.value.length = 0
		formData.value.push(...(result.form || []))
	} catch (error) {
		console.error(error)
		uni.showToast({ title: '获取审批信息失败', icon: 'error' })
	}
}

const initFlow = (rows: any[], flow: boolean): void => {
	isFlow.value = !!flow
	currentRows.value = rows
	activeName.value = 'audit'
	auditParam.reason = ''
	auditParam.value = -1

	if (flow) {
		currentOption = {
			table: rows[0].WorkTable,
			key: "WorkTableKey"
		}
	}
	
	getAuditInfo(currentOption)
}

// Lifecycle
onMounted(() => {
	const rows = [{
		WorkTable: props.data.workTable,
		WorkTableKey: props.data.tableKey
	}]
	initFlow(rows, true)
})

// Expose methods for external use
defineExpose({
	initFlow,
	getAuditInfo
})
</script>

<style lang="less" scoped>
.audit-model-content {
	padding: 10px;
}

.step-item {
	background: #fff;
	display: flex;
}

.left-item {
	min-width: 180px;
	text-align: right;
	padding-right: 25px;
	padding-top: 8px;

	.left-date {
		font-size: 13px;
		padding-top: 7px;
		color: #6c6c6c;
	}
}

.right-item {
	cursor: pointer;
	position: relative;
	border-bottom: 1px solid #f3f3f3;
	padding: 5px 0 5px 5px;
}

.left-item,
.right-item {
	padding-bottom: 10px;
}

.right-item:last-child {
	border-bottom: 0;
}

.step-line {
	top: 16px;
	left: -10px;
	width: 1px;
	height: 100%;
	position: absolute;
	background-color: #ebedf0;
}

.step-circle {
	position: absolute;
	top: 17px;
	left: -9px;
	z-index: 2;
	font-size: 12px;
	line-height: 1;
	transform: translate(-50%, -50%);
	width: 7px;
	height: 7px;
	background-color: #a1a1a1;
	border-radius: 50%;
}

.right-item::before {
	content: '';
}

.step-content {
	padding-top: 2px;
	font-size: 14px;
	color: #828282;
	line-height: 1.5;
}

.step-title {
	font-weight: bold;
	padding-top: 3px;
}

.step-text {
	font-size: 13px;
	color: #999999;
	padding-top: 6px;
}

.step-current {
	* {
		color: #2f95ff !important;
	}

	.step-circle {
		background: #2f95ff !important;
	}

	font-size: 13px;
	padding-top: 6px;
	color: black;
}

.audit-content {
	padding: 10px;
	border-radius: 4px;

	.fx-left {
		margin-top: 20rpx;
		flex: 1;

		.rd {
			display: flex;
			align-items: baseline;
		}
	}

	.fx-right {
		.btn {
			margin-top: 10px;
			text-align: center;
		}
	}
}

.cell-item {
	font-weight: 500;
}

.desc-top {
	padding: 5px 10px 0 10px;
}

.step-item-ad {
	* {
		color: #9f9898 !important;
	}
}

.f-item {
	padding: 20rpx;
	display: flex;
	color: rgb(48, 49, 51);
	font-size: 26rpx;
	border-bottom: 1px solid #f5f5f5;

	.f-name {
		width: 200rpx;
	}

	.f-value {
		flex: 1;
		text-align: right;
	}
}
</style>